package cn.razgriz.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    //在目标方法执行之前执行（在show方法之前）
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("preHandle执行");
        //如果不放行可以通过设置response进行重定向或者转发
        String param = request.getParameter("param");
        if(param != null && param.equals("yes")){
            return true;
        }
        response.setStatus(302);
        response.setHeader("location","https://www.baidu.com");
        return false;  //返回true代表放行，返回false代表不放行
    }

    @Override
    //在目标方法执行之后，视图返回之前执行（也就是show方法返回了ModelAndView,spring还没有返回视图给客户端的时候）
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //modelAndView可以设置其它的值，从而达到更改的目的
        System.out.println("postHandle执行");
    }

    @Override
    //在整个流程都执行完毕后，会执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("afterCompletion方法执行");
    }
}
